package com.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;

@Controller
@RequestMapping(value = "/file")
public class FileUploadController {

    private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);

    @RequestMapping(value = "/page")
   public String filePage() {
       return "fileupload";
   }

   @ResponseBody
   @RequestMapping(value = "/upload")
   public String upload(HttpServletRequest request, MultipartFile file) {
        try {
            String dir = request.getSession().getServletContext().getRealPath("/")+"upload/";
            File fileDir = new File(dir);
            if (!fileDir.exists()) {
                fileDir.mkdir();
            }
            String fileName = file.getOriginalFilename();
            File f = new File(dir + fileName);
            file.transferTo(f);
        } catch (Exception e) {
           logger.error("上传失败",e);
            return "failed";
        }
        return "success";
   }
}
